<template>
  <div>
    <Form :label-width="120" ref="form1" :model="form1">
      <Row v-show="!switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="二级集团：" prop="workDate">
            <Select v-model="form1.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="企业名称：" prop="orgId">
            <Select clearable filterable style="width:300px" v-model="form1.belongOrgName" placeholder="请选择企业"
                    :remote-method="remoteMethodSelectOrg"
                    :default-label="defaultLabel"
                    :loading="orgLoading">
              <Option v-for="(option, index) in orgLists" :value="option.orgName" :key="index">{{ option.orgName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <i-col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">展开
              <Icon type="ios-arrow-down"/>
            </Button>
          </div>
        </i-col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="二级集团：" prop="workDate">
            <Select v-model="form1.twoLevelOrgName" filterable>
              <Option v-for="item in twoLevelOrgs" :value="item.orgName" :key="item.orgId">{{ item.orgName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="企业名称：" prop="orgId">
            <Select clearable filterable style="width:300px" v-model="form1.belongOrgName" placeholder="请选择企业"
                    :remote-method="remoteMethodSelectOrg"
                    :default-label="defaultLabel"
                    :loading="orgLoading">
              <Option v-for="(option, index) in orgLists" :value="option.orgName" :key="index">{{ option.orgName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作业时间：" prop="ptwDate">
            <DatePicker type="date" v-model="form1.ptwDate" class="query-form-el" format="yyyy-MM-dd"
                        placeholder="请选择"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="所属单位：" prop="orgId">
            <cascaderDom class="query-form-el" style="padding-top: 2px" ref="childConOrg" @setOrgInfo="setQueryOrgId"
                         @setOrgname="setQueryOrgName" :currentOrgId="currentOrgId"
                         :rootOrgId="rootOrgId" :currentOrgName="currentOrgName" :orgTree="true"></cascaderDom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作业类型：" prop="ptwType">
            <Select class="query-form-el" filterable v-model="form1.ptwType">
              <Option v-for="item in ptwTypeList" :value="item.codingCodeId" :key="item.codingCodeId">{{
                  item.codingName
                }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="作业等级：">
            <Select class="query-form-el" filterable v-model="form1.workGrade">
              <Option v-for="item in workGradeList" :value="item.codingCodeId" :key="item.codingCodeId">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="24">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
          </div>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :loading="loading" border :columns="columns1" :data="dataTable"
           width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
    <Row type="flex" justify="end">
      <i-col>
        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total
              show-sizer show-elevator/>
      </i-col>
    </Row>
  </div>
</template>

<script>

var cascaderDom = () => import('@/components/cascader-dom.vue');
import {Api} from '../../../../api/index.js'
import {sessionStorage, cookie} from '../../../../common/cacheUtils.js';
import ticketRecordDetailView from './ticketRecordDetailView.vue'

export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      defaultLabel:sessionStorage('userId').getObject('userId').companyName,
      orgLists:[],
      userInfo: sessionStorage('userId').getObject('userId'),
      twoLevelOrgs: [],
      orgLoading:false,
      loading: false,
      rootOrgId: '',
      switchFlag: true,
      form1: {
        ptwDate:new Date()
      },
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      columns1: [
        {
          title: '序号',
          width: 100,
          align: 'center',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          minWidth: 150,
          title: '所属单位',
          key: 'colonyOrg',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '作业单位',
          key: 'operateOrg',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '作业地点',
          key: 'workSite',
          align: 'center'
        },
        {
          minWidth: 210,
          title: '作业类型',
          key: 'ptwTypeName',
          align: 'center'
        },
        {
          minWidth: 210,
          title: '作业等级',
          key: 'workGradeName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '作业时间',
          key: 'planStartTime',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.ptwDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '作业负责人',
          key: 'leaderUserName',
          align: 'center',
        },
        {
          title: '操作',
          align: 'center',
          key: 'view',
          fixed: 'right',
          minWidth: 200,
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.showData(params, 1);
                  }
                }
              }, '查看'),
            ]);
          }
        }
      ],
      currentOrgId: '',
      currentOrgName: '',
      setCurrentName: {},
      dataTable: [],
      add: false,
      ptwTypeList: [],
      workGradeList: [],
      tableHeight: 10,
      deleteRows: [],
    }
  },
  mounted() {
    this.queryTwoOrgInfo();
    this.rootOrgId = sessionStorage('userId').getObject('userId').orgInfo.parentId;
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 105;
    this.selectCodingSort();
    this.query();
  },
  methods: {
    queryTwoOrgInfo() {
      if (sessionStorage('userId').getObject('userId').companyId != '18000000') {
        this.twoLevelOrgs.push({
          orgId: sessionStorage('userId').getObject('userId').twoLevelOrgId,
          orgName: sessionStorage('userId').getObject('userId').twoLevelOrgName
        });
      } else {
        this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
          this.twoLevelOrgs = res.data.data
        }).catch(e => {
        })
      }
    },
    remoteMethodSelectOrg (query) {
      if (query !== '') {
        this.orgLists = [];
        this.orgLoading = true;
        this.$http.get(Api.queryOrgList+"?companyId="+ this.userInfo.companyId +"&orgName="+query+"&fromPage=1&pageSize=1000").then(res => {
          this.orgLists = res.data.data;
          this.orgLoading = false;
        }).catch(e => {
          this.orgLoading = false;
          this.$Message.error('请求失败');
        })
      } else {
        this.orgLoading = false;
      }
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 44;
      } else {
        this.tableHeight = this.tableHeight + 44;
      }
    },
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/ptw-100001', {params: {}}).then((res) => {
        this.ptwTypeList = res.data.data;
      })
      this.$http.get(Api.queryCodeDetailBySortId + '/ptw-100004', {params: {}}).then((res) => {
        this.workGradeList = res.data.data;
      })
    },
    setQueryOrgId(data) {
      this.form1.colonyOrgId = data[data.length - 1];
    },
    setQueryOrgName(data) {
      this.form1.colonyOrg = data;
    },

    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },

    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },

    showData(data, flag) {
      this.$router.push({name: 'ticketRecordDetailView', params: {'data': data}});
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    deleteData(params) {
      let url = Api.deletePTW;
      this.$http.get(url, {params: {ptwId: params.row.ptwId}}).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },

    query() {
      this.loading = true;
      let data = {
        currentPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        userId: sessionStorage('userId').getObject('userId').userId
      }
      if (this.form1.ptwDate != '' && this.form1.ptwDate != undefined) {
        this.form1.ptwDate = this.formatDate(new Date(this.form1.ptwDate), 'yyyy-MM-dd');
      } else {
        delete this.form1['ptwDate'];
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.getPtwList;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        this.pagedata.total = res.data.totalSize;
        this.loading = false;
        this.dataTable.forEach(item => {
          this.ptwTypeList.forEach(item1 => {
            if (item1.codingCodeId == item.ptwType)
              item.ptwTypeName = JSON.parse(JSON.stringify(item1.codingName));
            ;
          })
          this.workGradeList.forEach(item2 => {
            if (item2.codingCodeId == item.workGrade)
              item.workGradeName = item2.codingName;
          })
        })
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {ptwDate:new Date()};
      this.query();
    },
    addInfo() {
      let obj = null;
      this.$router.push({name: 'ticketDetailEdit', params: {'data': obj}});
    },
    updateInfo(row) {
      this.$router.push({name: 'ticketDetailUpdate', params: {'data': row}});
    },
    cancel() {

    },
    formatDate(date, fmt) {
      if (typeof date == 'string') {
        return date;
      }
      if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
      if (!date || date == null) return null;
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
      return fmt
    },
  }
}
</script>
<style lang='css' scoped>
@import '../../../../index.css';
</style>
